const puppeteer = require("puppeteer");
const GetElementData = require("./pages/getElementData.js");
const GetFetchData = require("./pages/getFetchData.js");
const createFile = require("./utils/createFile.js");
const download = require("./utils/download.js");
const { wait } = require("./utils/tools.js");
const dayjs = require("dayjs");

const url = "https://fanyi.youdao.com/index.html#/";
// const url = "https://www.baidu.com/";
// const url = "http://192.168.11.16:8023/";

// 定义数据
const eventMap = {
  ELEMENT: GetElementData, // 爬取元素数据
  FETCH: GetFetchData, // 爬取请求数据
};

/**
 * url  页面路径
 * event  ELEMENT 元素， FETCH 资源
 * type  查找不同的属性或值 src href text 改动点
 * selector  选择器
 */

// 查找 标签元素 img src
const tagImgSrcState = {
  url: url,
  event: "ELEMENT",
  selector: "img",
  type: "src",
};

// 查找 class元素 内容
const classContentState = {
  url: url,
  event: "ELEMENT",
  selector: "#s-top-left > a",
  type: "href",
};

const state = tagImgSrcState;

const runBrowser = async () => {
  // 启动浏览器
  const browser = await puppeteer.launch({
    // devtools: true,
    // slowMo: 1000,
    headless: false,
    args: ["--start-maximized"],
    defaultViewport: null,
  });

  // 创建一个新页面
  const page = await browser.newPage();

  // const pages = await browser.pages();
  // await page.setViewport({ width: 1920, height: 960 });

  // 访问一个网址
  await page.goto(state.url);

  // 爬取dom
  if (state.event == "ELEMENT") {
    const result = await eventMap["ELEMENT"](page, state);
    console.log(result, "result---");

    const fileName = dayjs(Date.now()).format("YYYY-MM-DD");
    createFile("D:\\down\\", fileName, async (dir) => {
      for (let index = 0; index < result.length; index++) {
        const element = result[index];
        download(element, dir, index);
        await wait(500);
      }
    });
  }

  // 爬取请求
  if (state.event == "FETCH") {
    const result = await eventMap["FETCH"](page, state, (url) => {
      console.log(url);
    });
    console.log(result, "result---");
  }

  // 关闭浏览器
  // setTimeout(async () => {
  //   await browser.close();
  // }, 2000);
};

runBrowser();
